package com.dnndo.web.controller.system;

import com.dnndo.common.constant.RedisConstant;
import com.dnndo.common.core.controller.BaseController;
import com.dnndo.common.core.domain.R;
import com.dnndo.common.core.domain.model.RegisterBody;
import com.dnndo.common.core.redis.RedisCache;
import com.dnndo.common.utils.StringUtils;
import com.dnndo.framework.web.service.SysRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 注册验证
 * 
 * @author ruoyi
 */
@RestController
public class SysRegisterController extends BaseController
{
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 用户注册
     * @param user 注册信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public R<?> register(@RequestBody @Validated RegisterBody user)
    {
        if (user.getSmsCode() == null || user.getSmsCode().isEmpty()) {
            return R.fail("验证码不能为空");
        }
        //验证短信验证码
        Boolean hasKey = redisCache.hasKey(RedisConstant.SMS_CODE_KEY + user.getUsername());
        if (!hasKey) {
            return R.fail("验证码错误");
        } else {
            String smsCode = redisCache.getCacheObject(RedisConstant.SMS_CODE_KEY + user.getUsername());
            if (!user.getSmsCode().equals(smsCode)) {
                return R.fail("验证码错误");
            } else {
                redisCache.deleteObject(RedisConstant.SMS_CODE_KEY + user.getUsername());
                redisCache.deleteObject(RedisConstant.SMS_CODE_COUNT_KEY + user.getUsername());
            }
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? R.ok() : R.fail(msg);
    }
}
